/**
 * <p>Copyright (c) 2014 ole.platform.All Rights Reserved.</p>
 * @author <a href="ole.platformjava@foxmail.com">ole.platform</a>
 */
package com.yjps.system.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSON;
import com.yjps.common.message.Message;
import com.yjps.common.page.Pager;
import com.yjps.system.model.Permission;
import com.yjps.system.model.Role;
import com.yjps.system.model.User;
import com.yjps.system.service.PermissionService;
import com.yjps.system.service.RoleService;
import com.yjps.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 角色管理控制类
 */
@Controller
@RequestMapping("/system/role")
public class RoleController
{
	private static final Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	RoleService roleService;
	@Autowired
	PermissionService permissionService;
	@Autowired
	UserService userService;

	/**
	 * 获得角色列表数据
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
        Pager<Role> pager = roleService.getRoleByPager(new Pager<Role>(request, response));
		List<Role> roleList = /*roleService.roleList();*/pager.getList();
		if(roleList != null && roleList.size() > 0) {
			for (Role role : roleList){
				List<Permission> permissions = role.getPermissions();
				StringBuilder sb = new StringBuilder();
				if(permissions != null && permissions.size()>0){
					for(Permission p : permissions) {
						sb.append(p.getPer_description()+",");
					}
				}
				role.setViewPermissions(sb.toString());
			}
		}
        model.addAttribute(pager);
		model.addAttribute("roleList",roleList);
		return "system/role/list";
	}






	@RequestMapping(value = "/edit",method = RequestMethod.GET)
	public String editForm(@RequestParam(value = "id", required = false)String id,Model model){
		if(!StringUtils.isEmpty(id)){
			Role role = roleService.findRole(Integer.parseInt(id));
			if(role != null){
				model.addAttribute("role", role);
			}
		}
		List<Permission>  permissions = permissionService.permissionList();
		model.addAttribute("permissions",permissions);
		return "system/role/edit";
	}
	@RequestMapping(value = "/edit",method = RequestMethod.POST)
	public String edit(Role role,HttpServletRequest request,Model model){
		if(role != null) {
			if (StringUtils.isEmpty(role.getId()) || role.getId()==0) {
				if (roleService.findRoleByName(role.getRolename()) != null) {
					model.addAttribute("role", role);
					Message message = new Message(false, "the rolename has exist");
					model.addAttribute("message", message);
					return "system/role/edit";
				}
				String[] permissions = request.getParameterValues("permission");
				List<Permission> permissionList = new ArrayList<>();
				if (permissions != null && permissions.length != 0) {
					for(String p:permissions) {
						Permission permission = permissionService.findPermission(Integer.parseInt(p));
						permissionList.add(permission);
					}
				}
				role.setPermissions(permissionList);
				role.setIsValid(1);
				roleService.addRole(role);
				log.debug("add role " + role.getRolename() + " success");
			}else {
				roleService.updateRole(role);
				log.debug("update role " + role.getRolename() + " success");
			}
		}
		return "redirect:/system/role/list";
	}

/*	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	public String delete(@RequestParam(value = "id",required = true)String id){
		roleService.deleteRole(Integer.parseInt(id));
		return "redirect:/system/role/list";
	}*/

	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	public String delete(@RequestParam(value = "id",required = true)String id,Model model){
		Message message = null;
		Role role = roleService.findRole(Integer.parseInt(id));
		//列出所有用户
		String type = "0";
		if(role != null) {
			List<User> users = userService.findUserList(type);
			for(User user : users){
				Set<Role> roles = user.getRoles();
				if(roles.contains(role)){
				log.debug("删除已有用户引用的角色不成功");
					message = new Message(false,"不能删除该角色");
					model.addAttribute("message", message);
					return "redirect:/system/role/list";
				}
			}
			roleService.deleteRole(Integer.parseInt(id));
		}
		message = new Message(true,"delete successfully ");
		return "redirect:/system/role/list";
	}
	@ResponseBody
	@RequestMapping(value = "/getRole",method = RequestMethod.GET)
	public String getRole(@RequestParam(value = "id",required = true)String id){
		Role role = roleService.findRole(Integer.parseInt(id));

		List<Permission>  permissions = permissionService.permissionList();
		role.setAllPermissions(permissions);
		String jsonString  = JSON.toJSONString(role);
		System.out.println("role json string is " +jsonString);
		return jsonString;
	}
}
